<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="客户昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入客户昵称"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="客户状态" prop="userStatus">
        <el-select v-model="queryParams.userStatus" placeholder="请选择状态" clearable style="width: 120px">
          <el-option label="正常" :value="0"></el-option>
          <el-option label="禁用" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="注册时间" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 240px"
          @change="handleDateRangeChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['car:customer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['car:customer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['car:customer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['car:customer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户ID" align="center" prop="id" width="80" />
      <el-table-column label="客户信息" align="left" min-width="200">
        <template slot-scope="scope">
          <div class="customer-info">
            <div class="customer-avatar">
              <el-avatar 
                :src="scope.row.avatarUrl" 
                :size="40"
                icon="el-icon-user-solid"
                @error="handleAvatarError">
              </el-avatar>
            </div>
            <div class="customer-details">
              <div class="customer-name">
                <span class="nickname">{{ scope.row.nickname || '未设置昵称' }}</span>
                <el-tag v-if="scope.row.userStatus === 0" type="success" size="mini">正常</el-tag>
                <el-tag v-else-if="scope.row.userStatus === 1" type="danger" size="mini">禁用</el-tag>
              </div>
              <div class="customer-contact">
                <i class="el-icon-phone"></i>
                <span>{{ scope.row.phone || '未绑定手机' }}</span>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="微信信息" align="center" min-width="150">
        <template slot-scope="scope">
          <div class="wechat-info">
            <div class="openid">
              <el-tooltip :content="scope.row.openid" placement="top">
                <span class="openid-text">{{ scope.row.openid.substring(0, 10) }}...</span>
              </el-tooltip>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后更新" align="center" prop="updateTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['car:customer:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['car:customer:edit']"
          >修改</el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['car:customer:edit', 'car:customer:remove']">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="toggleStatus" v-if="scope.row.userStatus === 0">
                <i class="el-icon-lock"></i>禁用客户
              </el-dropdown-item>
              <el-dropdown-item command="toggleStatus" v-else>
                <i class="el-icon-unlock"></i>启用客户
              </el-dropdown-item>
              <el-dropdown-item command="delete" divided>
                <i class="el-icon-delete"></i>删除客户
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="微信OpenID" prop="openid">
              <el-input v-model="form.openid" placeholder="请输入微信OpenID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户状态" prop="userStatus">
              <el-select v-model="form.userStatus" placeholder="请选择状态">
                <el-option label="正常" :value="0">
                  <i class="el-icon-check" style="color: #67C23A;"></i> 正常
                </el-option>
                <el-option label="禁用" :value="1">
                  <i class="el-icon-close" style="color: #F56C6C;"></i> 禁用
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户昵称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入客户昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11">
                <template slot="prepend">+86</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="头像URL" prop="avatarUrl">
          <div class="avatar-uploader">
            <el-input v-model="form.avatarUrl" placeholder="请输入头像URL或上传图片">
              <el-button slot="append" icon="el-icon-link">预览</el-button>
            </el-input>
            <div class="avatar-preview" v-if="form.avatarUrl">
              <el-avatar :src="form.avatarUrl" :size="60" icon="el-icon-user-solid"></el-avatar>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 客户详情对话框 -->
    <el-dialog title="客户详情" :visible.sync="detailOpen" width="600px" append-to-body>
      <div class="customer-detail" v-if="currentCustomer">
        <div class="detail-header">
          <el-avatar :src="currentCustomer.avatarUrl" :size="80" icon="el-icon-user-solid"></el-avatar>
          <div class="header-info">
            <h3>{{ currentCustomer.nickname || '未设置昵称' }}</h3>
            <el-tag v-if="currentCustomer.userStatus === 0" type="success">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </div>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户ID">{{ currentCustomer.id }}</el-descriptions-item>
          <el-descriptions-item label="微信OpenID">
            <el-tooltip :content="currentCustomer.openid" placement="top">
              <span>{{ currentCustomer.openid.substring(0, 15) }}...</span>
            </el-tooltip>
          </el-descriptions-item>
          <el-descriptions-item label="手机号码">{{ currentCustomer.phone || '未绑定' }}</el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ parseTime(currentCustomer.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="最后更新">{{ parseTime(currentCustomer.updateTime) }}</el-descriptions-item>
          <el-descriptions-item label="账户状态">
            <el-tag v-if="currentCustomer.userStatus === 0" type="success">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
        <el-button type="primary" @click="handleUpdate(currentCustomer)" v-hasPermi="['car:customer:edit']">编辑客户</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer } from "@/api/car/customer"

export default {
  name: "Customer",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户信息管理表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情对话框
      detailOpen: false,
      // 当前选中客户
      currentCustomer: null,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        openid: null,
        nickname: null,
        avatarUrl: null,
        phone: null,
        userStatus: null,
        beginTime: null,
        endTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        openid: [
          { required: true, message: "微信OpenID不能为空", trigger: "blur" },
          { min: 20, max: 50, message: "OpenID长度应在20到50个字符之间", trigger: "blur" }
        ],
        userStatus: [
          { required: true, message: "请选择客户状态", trigger: "change" }
        ],
        nickname: [
          { max: 32, message: "昵称长度不能超过32个字符", trigger: "blur" }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        avatarUrl: [
          { type: 'url', message: "请输入正确的URL地址", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询客户信息管理列表 */
    getList() {
      this.loading = true
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        openid: null,
        nickname: null,
        avatarUrl: null,
        phone: null,
        userStatus: 0,
        createTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 日期范围变化处理 */
    handleDateRangeChange(dateRange) {
      if (dateRange && dateRange.length === 2) {
        this.queryParams.beginTime = dateRange[0]
        this.queryParams.endTime = dateRange[1]
      } else {
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      }
    },
    /** 头像加载错误处理 */
    handleAvatarError() {
      return true
    },
    /** 查看客户详情 */
    handleView(row) {
      this.currentCustomer = row
      this.detailOpen = true
    },
    /** 下拉菜单命令处理 */
    handleCommand(command, row) {
      switch (command) {
        case 'toggleStatus':
          this.toggleCustomerStatus(row)
          break
        case 'delete':
          this.handleDelete(row)
          break
      }
    },
    /** 切换客户状态 */
    toggleCustomerStatus(row) {
      const status = row.userStatus === 0 ? 1 : 0
      const statusText = status === 0 ? '启用' : '禁用'
      
      this.$modal.confirm(`确认要${statusText}客户"${row.nickname || row.openid}"吗？`).then(() => {
        const updateData = { ...row, userStatus: status }
        updateCustomer(updateData).then(response => {
          this.$modal.msgSuccess(`${statusText}成功`)
          this.getList()
        }).catch(error => {
          this.$modal.msgError(`${statusText}失败：` + (error.msg || error.message || "未知错误"))
        })
      }).catch(() => {})
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.queryParams.beginTime = null
      this.queryParams.endTime = null
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加客户信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改客户信息"
        this.detailOpen = false
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除客户信息管理编号为"' + ids + '"的数据项？').then(function() {
        return delCustomer(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('car/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.customer-info {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.customer-avatar {
  margin-right: 12px;
}

.customer-details {
  flex: 1;
}

.customer-name {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.nickname {
  font-weight: 500;
  margin-right: 8px;
  color: #303133;
}

.customer-contact {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #909399;
}

.customer-contact i {
  margin-right: 4px;
}

.wechat-info {
  text-align: center;
}

.openid-text {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #666;
  cursor: pointer;
}

.openid-text:hover {
  color: #409eff;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  font-size: 12px;
}

.el-dropdown-link:hover {
  color: #66b1ff;
}

.avatar-uploader {
  display: flex;
  align-items: flex-start;
}

.avatar-preview {
  margin-left: 12px;
  padding: 8px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
}

.customer-detail .detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.customer-detail .header-info {
  margin-left: 20px;
}

.customer-detail .header-info h3 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 500;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-select {
  width: 100%;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f8f9fa;
  color: #495057;
  font-weight: 500;
}

.el-table td {
  border-bottom: 1px solid #f0f0f0;
}

.el-table .el-table__row:hover > td {
  background-color: #f8f9ff;
}

/* 状态标签样式 */
.el-tag {
  font-weight: 500;
  border-radius: 12px;
}

.el-tag.el-tag--success {
  background-color: #f0f9ff;
  border-color: #c6f7e9;
  color: #67c23a;
}

.el-tag.el-tag--danger {
  background-color: #fef0f0;
  border-color: #fbc4c4;
  color: #f56c6c;
}

/* 表单布局优化 */
.el-row {
  margin-bottom: 0;
}

.el-col {
  padding-right: 10px;
  padding-left: 10px;
}

/* 搜索表单样式 */
.el-form--inline .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

/* 对话框样式 */
.el-dialog__body {
  padding: 20px 20px 10px 20px;
}

.el-descriptions {
  margin-top: 20px;
}

.el-descriptions-item__label {
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .customer-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .customer-avatar {
    margin-bottom: 8px;
  }
  
  .el-form--inline .el-form-item {
    display: block;
    margin-bottom: 15px;
  }
}
</style>
